package cs2340.todolist.model.account_management;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.content.Context;
import android.util.Log;
import cs2340.todolist.model.ToDoItem;
import cs2340.todolist.model.ToDoList;
import cs2340.todolist.model.User;
import cs2340.todolist.model.sqlite_database.ToDoItemDataSource;
import cs2340.todolist.model.utility.SearchEngine;
import cs2340.todolist.model.utility.SearchEngine.Filter;

/**
 * populate a todolist with items from the database, search the list, etc
 * @author BaoTam
 *
 */
public class ToDoListManager {
	private final ToDoItemDataSource dataSource;
	private final ToDoList 		toDoList;
	private final User			user;
	private SearchEngine 		searchEngine;
	private Context	 			context;
	
	/**
	 * constructor sets up a ToDoListManager with the given user
	 * contract: user has to be in the database and has to hold a valid id
	 * @param context
	 * @param user
	 */
	public ToDoListManager(Context context, User user) {
		this.context 	= context;
		this.user 		= user;
		this.dataSource = new ToDoItemDataSource(context);
		this.toDoList 	= new ToDoList();
	}
	
	/**
	 * populate the todolist with todoitems associated with the current user
	 */
	public void fetchToDoItems() {
		System.out.println("datasource: " + dataSource);
		dataSource.open();
		Log.d("fetchToDoItems", "start fetching");
		List<ToDoItem> returnItem = dataSource.getItemsByUserId(user.getId());
		dataSource.close();
		System.out.println(returnItem);
		toDoList.addMultipleItems(returnItem);
	}
	
	/**
	 * @return an iterator of the todolist
	 */
	public Iterator<ToDoItem> getToDoListIterator(Filter filter) {
		ArrayList<ToDoItem> filterResults = (ArrayList<ToDoItem>) toDoList.getToDoItems();
		filter.filter(filterResults);
		return filterResults.iterator();
	}
	
	public ToDoList getToDoList() {
		return toDoList;
	}
	
	
	/**
	 * @return the search engine for the list
	 */
	public SearchEngine getSearchEngine() {
		return searchEngine;
	}
	
	/**
	 * @param searchEngine that will be used to filter the list
	 */
	public void setSearchEngine(SearchEngine searchEngine) {
		this.searchEngine = searchEngine;
	}
	
	/**
	 * @return the current context
	 */
	public Context getContext() {
		return context;
	}
	
	/**
	 * @param context to replace the old one
	 */
	public void setContext(Context context) {
		this.context = context;
		dataSource.setContext(context);
	}
	
}
